import { create } from 'zustand';

interface AudioState {
  audio: HTMLAudioElement | null;
  isPlaying: boolean;
  currentTime: number;
  setAudio: (audio: HTMLAudioElement | null) => void;
  setIsPlaying: (isPlaying: boolean) => void;
  setCurrentTime: (time: number) => void;
  stopCurrentAudio: () => void;
}

export const useAudioStore = create<AudioState>((set, get) => ({
  audio: null,
  isPlaying: false,
  currentTime: 0,
  setAudio: (audio) => set({ audio }),
  setIsPlaying: (isPlaying) => set({ isPlaying }),
  setCurrentTime: (time) => set({ currentTime: time }),
  stopCurrentAudio: () => {
    const { audio } = get();
    if (audio) {
      audio.pause();
      audio.currentTime = 0;
      set({ isPlaying: false, currentTime: 0 });
    }
  },
}));

export const playAudio = async (url: string): Promise<HTMLAudioElement> => {
  const { audio: currentAudio, setAudio, setIsPlaying, setCurrentTime } = useAudioStore.getState();

  // Stop current audio if playing
  if (currentAudio) {
    currentAudio.pause();
    currentAudio.currentTime = 0;
  }

  const audio = new Audio(url);
  
  audio.addEventListener('timeupdate', () => {
    setCurrentTime(audio.currentTime);
  });

  audio.addEventListener('ended', () => {
    setIsPlaying(false);
    setCurrentTime(0);
  });

  setAudio(audio);
  setIsPlaying(true);
  await audio.play();

  return audio;
};

export const toggleAudio = async () => {
  const { audio, isPlaying, currentTime, setIsPlaying } = useAudioStore.getState();

  if (!audio) return;

  if (isPlaying) {
    audio.pause();
    setIsPlaying(false);
  } else {
    audio.currentTime = currentTime;
    await audio.play();
    setIsPlaying(true);
  }
};